/*
 * IFAS_AIS_SN.c
 *
 * Created: 12/13/2013 2:13:50 AM
 *  Author: Tim
 */ 


#include <avr/io.h>
#include <util/delay.h>
#include <stdio.h>
#include "adc.h"
#include "clock.h"
#include "uart.h"

#define _5V_TRIGGER_EN()	(PORTC.DIRSET = 0x01)
#define _5V_TRIGGER_ON()	(PORTC.OUTSET = 0x01)
#define _5V_TRIGGER_OFF()	(PORTC.OUTCLR = 0x01)

#define AMP_EN()	(PORTC.DIRSET = 0x10)
#define AMP_ON()	(PORTC.OUTCLR = 0x10)
#define AMP_OFF()	(PORTC.OUTSET = 0x10)

#define SMS0_EN()	(PORTF.DIRSET = 0x02)
#define SMS0_ON()	(PORTF.OUTSET = 0x02)
#define SMS0_OFF()	(PORTF.OUTCLR = 0x02)

#define XBee_EN()	(PORTE.DIRSET = 0x01)
#define XBee_OFF()	(PORTE.OUTCLR = 0x01)
#define XBee_ON()	(PORTE.OUTSET = 0x01)


/* 
//nope because fail

#define BATT_REF_EN()
#define BATT_REF_ON()
#define BATT_REF_OFF()
*/

#define RS232_FORCEOFF_msk	(1<<4)
#define RS232_ENABLE_msk	(1<<1)

void rs232PowerEnable()
{
	PORTD.DIRSET = RS232_ENABLE_msk | RS232_FORCEOFF_msk;
}

void rs232PowerOn()
{
	PORTD.OUTSET = RS232_FORCEOFF_msk;
	PORTD.OUTCLR = RS232_ENABLE_msk;
}

void rs232PowerOff()
{
	PORTD.OUTCLR = RS232_FORCEOFF_msk;
	PORTD.OUTSET = RS232_ENABLE_msk;
}

int main(void)
{
	clockInit();
//	adcInit();
	rs232PowerEnable();
	rs232PowerOff();
	
	//XBee_EN();
	//XBee_ON();
	
	usbInit(9600);
	rs232Init(9600);
	XBeeInit(9600);
	
	SMS0_EN();
	SMS0_OFF();
	_5V_TRIGGER_EN();
	_5V_TRIGGER_OFF();
	AMP_EN();
	AMP_OFF();
//	_delay_ms(1000);
//    _5V_TRIGGER_OFF();
	sei();
	while(1)
    {
		
		if(dataInBufE0())
		{
			char msg;
			fscanf(&XBee_str,"%c",&msg);
			fprintf(&XBee_str,"%c\r\n",msg);
		}
		
		//fprintf(&XBee_str,"hello world\r\n");
		//_delay_ms(100);
		/*
		_5V_TRIGGER_ON();
		SMS0_ON();
		_delay_ms(3000);
		_5V_TRIGGER_OFF();
		SMS0_OFF();
		_delay_ms(3000);
        */
		
	//	fprintf(&USB_str,"hello world\r\n");
	//	fprintf(&RS232_str,"hello world\r\n");
	//	fprintf(&XBee_str,"soil moisture 0 = %f\r\n",1.65*analogRead(1)/8191.0);
	//	_delay_ms(100);
		//TODO:: Please write your application code 
    }
}